<?php

/**
 * Work.php
 * 
 * Work异常(Exception_Work)类
 * 
 * @author wang <wang@fvzone.com> 
 * @copyright Copyright (c) 2010 Fire vision Software Studio
 * @link http://www.fvzone.com
 * @license New BSD License.{@link http://www.opensource.org/licenses/bsd-license.php}
 * @version $Id: WorkException.php 1.0 2010-11-3 22:02:01Z wang $
 * @package exception
 * @since 1.0
 */

defined('IN_WORK') or exit('Authorization error');

/**
 * 调试信息类，用于记录调试信息
 */
class Exception_Work extends Exception
{
    public $type = null;

    public $level = array(1 => 'E_ERROR',
        2 => 'E_WARNING',
        4 => 'E_PARSE',
        8 => 'E_NOTICE',
        16 => 'E_CORE_ERROR',
        32 => 'E_CORE_WARNING',
        64 => 'E_COMPILE_ERROR',
        128 => 'E_COMPILE_WARNING',
        256 => 'E_USER_ERROR',
        512 => 'E_USER_WARNING',
        1024 => 'E_USER_NOTICE',
        2047 => 'E_ALL',
        2048 => 'E_STRICT',
        'custom' => 'E_USER_THROW_ERROR',
        );

    /**
     * 构造函数
     * 
     * @param string $message 提示信息
     * @param int $type 错误来源类型，如果是异常是异常类名
     * @param int $code 提示代号
     * @param string $file 出错的文件名
     * @param int $line 出错的行号
     */
    public function __construct($message, $type = null, $code = 0, $file = null, $line = 0)
    {
        parent::__construct($message, $code);

        $code = $code == 0    ? $this->getCode() : $code;
        $file = $file == null ? $this->getFile() : $file;
        $line = $line == 0    ? $this->getLine() : $line;

        $trace = $this->getTrace();

        for ($i = count($trace) - 1; $i > 0; --$i)
        {
            if (isset($trace[$i - 1]['args']))
            { 
                // Re-position the args
                $trace[$i]['args'] = $trace[$i - 1]['args']; 
                // Remove the args
                unset($trace[$i - 1]['args']);
            }
        } 
        // 用户抛出的异常
        if ($type == 'custom')
        {
            $code = $type;
            $file = $trace[0]['file'];
            $line = $trace[0]['line'];
            unset($trace[0]);
        }

        $level = isset($this->level[$code]) ? $this->level[$code] : $code; 
        // 如果开启了日志记录，则写入日志
        if (DEBUG_LOG == true)
        {
            Log::write($message);
        }
        $exception_file = PUBLIC_DIR . 'views/error/exception.tpl.php';
        is_file($exception_file) ? include_once $exception_file : include_once WORK_DIR . 'assets/views/exception.tpl.php';
        exit;
    }

    /**
     * 默认异常处理函数
     */
    public static function exception_handler(Exception $e)
    {
        $type = get_class($e);
        throw new Exception_Work($e->getMessage(), $type, $e->getCode(), $e->getFile(), $e->getLine());
    }
    /**
     * 默认错误处理函数
     */
    public static function error_handler($code, $message, $file, $line)
    {
        throw new Exception_Work($message, 'error_handler', $code, $file, $line);
    }
}